
import React, { Component } from 'react'
import { Toast, Modal, Popover, Flex } from 'antd-mobile';
import * as Fetch from './../utils/http.js'

// import {resDatas} from './../utils/data'

import store from './../../store/index'
function loadingToast(msg) {
    Toast.loading(msg, 0, () => {

    });
}
const alert = Modal.alert;
const Item = Popover.Item;
export default class GetAddress extends Component {

    constructor(props) {
        super(props)
        this.state = {
            district: '请稍后...',
            visible: false
        }
    }
    componentDidMount() {
        if(store.getState().weather.city){
            let res = {
                result:store.getState().weather
            }
            this.setState({district:'北京'})
            this.props.getdetail(res)
        }else{
          // this.getData('北京')
            this.GetCode()
        }
    }
    showAlert = (alertText) => {
        alert('提示', alertText, [
            { text: '确认', onPress: () => console.log('ok') },
        ]);
    }
    getData = (city) => {
        let requ = {
            "city": city
        }
        Fetch.post('https://www.jiaoguoliang.com/php_project/my_react/NEWGETWEATHER.php', requ).then((response) => {
        //   console.log(JSON.stringify(response))  
        if (response) {
                this.props.getdetail(response)
            }
        });
    }
    GetCode = () => {
        this.loadingActive = true
        let map, geolocation, AMap = window.AMap;
        map = new AMap.Map('container', { resizeEnable: true });
        map.plugin('AMap.Geolocation', () => {
            geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,
                timeout: 20000,
                buttonOffset: new AMap.Pixel(10, 20),
                zoomToAccuracy: true,
                buttonPosition: 'RB'
            });
            geolocation.getCurrentPosition();
            if (this.state.district !== '请稍后...') {
                this.setState({ district: '请稍后...' })
            }
            loadingToast('请稍后...')
            AMap.event.addListener(geolocation, 'complete', (data) => {
                // console.log('定位成功===>')
                // console.log('经度：' + data.position.getLng())
                // console.log('纬度：' + data.position.getLat())
                // console.log('精度：' + data.accuracy + '米')
                // console.log('是否经过偏移：' + (data.isConverted ? '是' : '否'))
                this.regeocoder([data.position.getLng(), data.position.getLat()], (result) => {
                    //   console.log('定位地址------>>>', result)
                    this.setState({
                        district: result.province + result.district
                    }, () => {
                        let msg = result.province.indexOf("市") !== -1 ? result.province : result.city
                        this.getData(msg)
                        Toast.hide()
                    })
                })
            });
            AMap.event.addListener(geolocation, 'error', (data) => {
               //  console.log('定位失败===>' + data.message)
                this.setState({
                    district: '定位失败'
                })
                this.showAlert('定位失败')
                this.getData('北京')
                Toast.hide()
            });
        });
    }

    regeocoder = (lnglatXY, complete) => {
        let resultInfo = {}
        let geocoder = new window.AMap.Geocoder({ radius: 1000, extensions: "all" });
        geocoder.getAddress(lnglatXY, (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
                let addressComponent = result.regeocode.addressComponent;
                resultInfo = {
                    address: result.regeocode.formattedAddress,
                    province: addressComponent.province,
                    city: addressComponent.city,
                    citycode: addressComponent.citycode,
                    district: addressComponent.district,
                    adcode: addressComponent.adcode,
                    township: addressComponent.township,
                    street: addressComponent.street,
                    streetNumber: addressComponent.streetNumber,
                    neighborhood: addressComponent.neighborhood,
                    neighborhoodType: addressComponent.neighborhoodType,
                    building: addressComponent.building
                }
                complete(resultInfo)
            }
        })
    }
    onSelect = (opt) => {
        let active = this.state.visible
        this.setState({
            visible: !active
        });
        if (opt.props.value === 'week') {
            this.props.goToUrl('week')
        }
    };
    handleVisibleChange = (visible) => {
        this.setState({
            visible
        });
    };
    render() {
        let styleColor = {
            // color: '#fff'
        }
        return (
            <Flex className='address'>
                <Flex.Item className='text-left'>
                    <span onClick={this.GetCode} className='iconfont icon-dingwei' style={styleColor}></span>
                </Flex.Item>
                <Flex.Item style={styleColor} className='text-center'>
                    {
                        this.state.district === '定位失败' ?
                            <span>北京</span>
                            :
                            <span>{this.state.district}</span>
                    }
                </Flex.Item>
                <Flex.Item className='text-right'>
                    <Popover mask
                        overlayClassName="fortest"
                        overlayStyle={{ color: 'currentColor' }}
                        visible={this.state.visible}
                        overlay={[
                            (<Item key="4" value="week" data-seed="week">一周天气</Item>),
                        ]}
                        align={{
                            overflow: { adjustY: 0, adjustX: 0 },
                            offset: [-10, 0],
                        }}
                        onVisibleChange={this.handleVisibleChange}
                        onSelect={this.onSelect}
                    >
                        <div style={{
                            height: '100%',
                            padding: '0 15px',
                            marginRight: '-15px',
                            fontSize: '1.4rem',
                            justifyContent: 'right'
                        }}
                        >
                            <span className='iconfont icon-liebiao1 address-detail'></span>
                        </div>
                    </Popover>
                </Flex.Item>
            </Flex>
        )
    }
}